//
//  SJOAuthViewController.swift
//  SJWeiboSwift
//
//  Created by app;e on 15/10/2.
//  Copyright © 2015年 world. All rights reserved.
//
//  点击登陆的授权页面

//App Key：454764644
//App Secret：883c3dc61d7a64ef96f26b0fb1423019
//授权回调页：http://www.baidu.com

import UIKit
import SVProgressHUD //使用import导入框架,系统会自动将OC转换为swift

class SJOAuthViewController: UIViewController,UIWebViewDelegate {

    private let WeiBo_Client_Id     = "454764644"
    private let WeiBo_Redirect_Uri  = "http://www.baidu.com"
    private let WeiBo_Client_Secret = "883c3dc61d7a64ef96f26b0fb1423019"
    private let WeiBo_Grant_Type    = "authorization_code"
    
    var webView:UIWebView?
    override func loadView() {
         webView = UIWebView()
        //设置代理
        webView?.delegate = self
        view = webView
        
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Done, target: self, action: "close")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadOAuth()

    }
    ///加载授权页面
    private func loadOAuth(){
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiBo_Client_Id)&redirect_uri=\(WeiBo_Redirect_Uri)"
        let url = NSURL(string: urlString)!
        let request = NSURLRequest(URL: url)
        webView?.loadRequest(request)

    }
    
    // MARK: - webView的代理方法
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        /*
        //请求授权
        https://api.weibo.com/oauth2/authorize?client_id=454764644&redirect_uri=http://www.baidu.com
        //授权成功返回的code
        http://www.baidu.com/?code=5fba3153978fec4854db41cb63f79684

        */

        //获取请求的url的完整字符串
        let urlString = request.URL!.absoluteString

        //如果url带weibo..需要加载. 如果是带baidu..的则不需要加载返回false
        if !urlString.hasPrefix("http://www.baidu.com"){
            return true
        }
        
        //判断回调的url是否包含code
        //获取请求中URL中的查询字符串
        let queryString = request.URL!.query!
        let code = "code="
        if (queryString.hasPrefix(code) ) {
            
            //截取code
            let codeString = (queryString as NSString).substringFromIndex((code as NSString).length)
            loadTokenWithCode(codeString)
        }
        
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    ///获取token
    private func loadTokenWithCode(code:String){
        //1.url:https://api.weibo.com/oauth2/access_token
        let urlString = "oauth2/access_token"
        //2.参数字典
        let param = ["client_id":WeiBo_Client_Id,
                     "client_secret":WeiBo_Client_Secret,
                     "grant_type":WeiBo_Grant_Type,
                     "redirect_uri":WeiBo_Redirect_Uri,
                     "code":code]
        
        SJNetWorkTools.sharedNetWorkTools().POST(urlString, parameters: param, success: { (_, json) -> Void in
            
            //将字典转userAccount模型
//            let userAccount = SJUserAccount(dic: json as! [String:AnyObject])
            //加载用户信息
            SJUserAccount(dic: json as! [String:AnyObject]).loadUserInfo { (account, error) -> () in
                
                //判断加载信息是否成功
                if account != nil {
                    sharedUserAccount = account
                    //加载成功,发送通知切换控制器
                    //object:为false 表示切换到welcomeVC
                    NSNotificationCenter.defaultCenter().postNotificationName(SJSwitchRootVCNotification, object: false)
                    
                    //关闭当前控制
                    self.close()
                    return
                }
                print(error)
                SVProgressHUD.showInfoWithStatus("网络不给力")
            }
            
            }) { (_, error) -> Void in
                print(error)
                SVProgressHUD.showInfoWithStatus("网络不给力")
        }
        
    }
    ///关闭当前控制器
    func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }

    
}
